package com.yxhl.zoume.core.tripsmgmt.ui.fragment.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yxhl.protobuf.BizOrder;
import com.yxhl.protobuf.OrderBizType;
import com.yxhl.zoume.R;
import com.yxhl.zoume.account.event.UserLoginEvent;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.car.model.PayResultEvent;
import com.yxhl.zoume.core.func.appraisal.model.CommentOnDriverEvent;
import com.yxhl.zoume.core.func.pay.model.CarPaymentEntrance;
import com.yxhl.zoume.core.func.pay.model.event.PaymentSuccessfulEvent;
import com.yxhl.zoume.core.specialcar.model.CarPaymentInfo;
import com.yxhl.zoume.core.tripsmgmt.presenter.home.CurrentTripsPresenter;
import com.yxhl.zoume.core.tripsmgmt.ui.adapter.CurrentTripsAdapter;
import com.yxhl.zoume.core.tripsmgmt.ui.event.CancelTripOrderEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.event.ComeBackFromTicketCodeEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.event.NavToPaymentEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.event.NavToTicketCodeEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.event.NavToTripDetailEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.event.ShowTicketCodeEvent;
import com.yxhl.zoume.core.tripsmgmt.ui.fragment.dialog.GetTicketCodeDialogFragment;
import com.yxhl.zoume.core.tripsmgmt.view.home.CurrentTripsView;
import com.yxhl.zoume.di.component.trip.DaggerTripComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.di.module.trip.TripModule;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * 项目名称：Ferrari
 * Created by menggod on 16/11/29 .
 * 当前行程列表
 */
public class CurrentTripsFragment extends BaseFragment implements CurrentTripsView,
        BaseQuickAdapter.RequestLoadMoreListener,
        SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "CurrentTripsFrag";

    //widgets
    @BindView(R.id.srl_include_refresh_layout)
    protected SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.recycler_include_recycler_view)
    protected RecyclerView mRecyclerView;

    @BindView(R.id.iv_include_refresh_no_record)
    protected ImageView mNoRecordIv;

    //arguments
    protected List<BizOrder> mDataList;
    private boolean isRefreshCleanList = false;

    /**
     * 是否需要加载网络数据
     */
    public static boolean sNeedLoadData = true;
    private CarPaymentEntrance mCarPaymentEntrance;

    //arguments
    @Inject
    CurrentTripsPresenter mCurrentTripsPresenter;
    private CurrentTripsAdapter mCurrentTripsAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LOG.e(TAG, "onCreate");
        onRxBusEvent();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LOG.e(TAG, "onCreateView savedInstanceState=" + savedInstanceState);
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mCurrentTripsPresenter.attachView(this);
        LOG.e(TAG, "sNeedLoadData=" + sNeedLoadData);
        if (sNeedLoadData) {
            loadCurrentTripsData();
            sNeedLoadData= false;
        }
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initAdapter();
        initSwipeRefresh();
        initRecycleView();
     //   loadCurrentTripsData();
    }

    @Override
    public void onStart() {
        super.onStart();
  //      loadCurrentTripsData();
    }

    @Override
    public void onResume() {
        super.onResume();
        LOG.e(TAG, "onResume");
        mCurrentTripsPresenter.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        LOG.e(TAG, "onPause");
        mCurrentTripsPresenter.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        LOG.e(TAG, "onDestroyView");
    }

    @Override
    public void onDestroy() {
        LOG.e(TAG, "onDestroy");
        mCurrentTripsPresenter.onDestroy();
        super.onDestroy();
    }

    public CurrentTripsFragment() {
        // Required empty public constructor
    }

    public static CurrentTripsFragment newInstance() {
        CurrentTripsFragment fragment = new CurrentTripsFragment();
        return fragment;
    }

    private void onRxBusEvent() {
        //跳到行程详情
        getSubscription().add(toSubscription(NavToTripDetailEvent.class,
                new Action1<NavToTripDetailEvent>() {
                    @Override
                    public void call(NavToTripDetailEvent navToTripDetailEvent) {
                        getAppComponent().navigator().navigateToDetailTripContainerActivity(
                                getActivity(),
                                navToTripDetailEvent.getShareView(),
                                navToTripDetailEvent.getBizOrder());
                    }
                }
        ));
        //跳到支付页面
        getSubscription().add(toSubscription(NavToPaymentEvent.class,
                new Action1<NavToPaymentEvent>() {
                    @Override
                    public void call(NavToPaymentEvent navToPaymentEvent) {
                        BizOrder bizOrder = navToPaymentEvent.getBizOrder();
                        OrderBizType bizType = bizOrder.getBizType();
                        switch (bizType) {
                            case SPECIAL_BUS_TIME:
                            case SPECIAL_BUS_WAY:
                            case ORDER_BIZ_SHARE:
                            case ORDER_BIZ_CHARTER: {
                                CarPaymentInfo specialCarPaymentInfo = getSpecialCarPaymentInfo(bizOrder);
                                getAppComponent().navigator().navigateToSpecialCarPayment(getActivity(), specialCarPaymentInfo);
                               // navigateToSpecialCarPayment
                                break;
                            }
                            default: {
                                getAppComponent().navigator().navigateToPayment(getActivity(), bizOrder);
                                break;
                            }
                        }
                    }
                }
        ));
        //跳到我的车票
        getSubscription().add(toSubscription(NavToTicketCodeEvent.class,
                new Action1<NavToTicketCodeEvent>() {
                    @Override
                    public void call(NavToTicketCodeEvent navToTicketCodeEvent) {
                        getAppComponent().navigator().navigateToTicketCodeActivity(
                                getActivity(),
                                navToTicketCodeEvent.getOrderSerial(),
                                navToTicketCodeEvent.getBizType());
                    }
                }
        ));

        getSubscription().add(toSubscription(ShowTicketCodeEvent.class,
                new Action1<ShowTicketCodeEvent>() {
                    @Override
                    public void call(ShowTicketCodeEvent showTicketCodeEvent) {
                        GetTicketCodeDialogFragment
                                .newInstance(showTicketCodeEvent.getVerifyCode())
                                .show(getFragmentManager(), "GetTicketCode");
                    }
                }
        ));
        //各行程详情里取消订单时
        getSubscription().add(toSubscription(
                CancelTripOrderEvent.class,
                new Action1<CancelTripOrderEvent>() {
                    @Override
                    public void call(CancelTripOrderEvent cancelTripOrderEvent) {
                        LOG.e(TAG, "call CancelTripOrderEvent");
                        String bizOrderId = cancelTripOrderEvent.getBizOrderId();
                        if (!TextUtils.isEmpty(bizOrderId)) {
                            for (BizOrder b : mDataList) {
                                LOG.e(TAG, "call getOrderSerial=" + b.getOrderSerial());
                                if (bizOrderId.equals(b.getOrderSerial())) {
                                    mDataList.remove(b);
                                    mCurrentTripsAdapter.notifyDataSetChanged();
                                    break;
                                }
                            }
                        }
                    }
                }
        ));
        //登录成功
        getSubscription().add(toSubscription(UserLoginEvent.class,
                new Action1<UserLoginEvent>() {
                    @Override
                    public void call(UserLoginEvent userLoginEvent) {
                        loadCurrentTripsData();
                    }
                }
        ));
        //支付成功时
        getSubscription().add(toSubscription(PaymentSuccessfulEvent.class,
                new Action1<PaymentSuccessfulEvent>() {
                    @Override
                    public void call(PaymentSuccessfulEvent paymentSuccessfulEvent) {
                        loadCurrentTripsData();
                    }
                }
        ));
        //我的车票
        getSubscription().add(toSubscription(ComeBackFromTicketCodeEvent.class,
                new Action1<ComeBackFromTicketCodeEvent>() {
                    @Override
                    public void call(ComeBackFromTicketCodeEvent comeBackFromTicketCodeEvent) {
                        loadCurrentTripsData();
                    }
                }
        ));
        //快车支付成功
        getSubscription().add(toSubscription(
                PayResultEvent.class,
                new Action1<PayResultEvent>() {
                    @Override
                    public void call(PayResultEvent payResultEvent) {
                        switch (payResultEvent.getPayStatus()) {
                            case STATUS_ENUM_TRUE: {
                                loadCurrentTripsData();
                                break;
                            }
                        }
                    }
                }
        ));
//快车评价成功
        getSubscription().add(toSubscription(
                CommentOnDriverEvent.class,
                new Action1<CommentOnDriverEvent>() {
                    @Override
                    public void call(CommentOnDriverEvent commentOnDriverEvent) {
                        loadCurrentTripsData();
                    }
                }
        ));
    }


    /**
     * 测试
     */
    private void initSwipeRefresh() {
        mSwipeRefreshLayout.setColorSchemeResources(
                R.color.bg_color_orange,
                R.color.bg_color_green,
                R.color.colorAccent);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }

    private void initAdapter() {
        if (mDataList == null) {
            mDataList = new ArrayList<>();
        } else {
            mDataList.clear();
        }
        mCurrentTripsAdapter = new CurrentTripsAdapter(mDataList);
        mCurrentTripsAdapter.setOnLoadMoreListener(this);
        int size = mCurrentTripsAdapter.getData().size();
        if (size == 0) {
            mNoRecordIv.setVisibility(View.VISIBLE);
        } else {
            mNoRecordIv.setVisibility(View.INVISIBLE);
        }
    }

    private void initRecycleView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mCurrentTripsAdapter);

    }


    @Override
    public void renderDataOnSuccess(List<BizOrder> orderList) {
        if (isRefreshCleanList) {
            mDataList.clear();
            isRefreshCleanList = false;
            PromptUtils.showShort(mActivity, "刷新完成");
        }

        mDataList.addAll(orderList);
        mCurrentTripsAdapter.setNewData(mDataList);
        int size = mCurrentTripsAdapter.getData().size();
        if (size == 0) {
            mNoRecordIv.setVisibility(View.VISIBLE);
        } else {
            mNoRecordIv.setVisibility(View.INVISIBLE);
        }
        if (orderList.size() < 10) {
            mCurrentTripsAdapter.loadMoreEnd();
        } else {
            mCurrentTripsAdapter.loadMoreComplete();
        }
        resetViewControlStatus();
        stopRefresh();
    }

    @Override
    public void renderDataOnFailure(String errorMessage) {
        mCurrentTripsAdapter.loadMoreFail();
        resetViewControlStatus();
        PromptUtils.showShort(mActivity, errorMessage);
    }

    @Override
    public void renderDataOnError() {
        resetViewControlStatus();
    }

    @Override
    public void closeDownRefresh() {
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }


    private CarPaymentInfo getSpecialCarPaymentInfo(BizOrder bizOrder) {

        OrderBizType bizType = bizOrder.getBizType();
        switch (bizType) {
            case ORDER_BIZ_SHARE:
                mCarPaymentEntrance = CarPaymentEntrance.CAR_PAYMENT_ENTRANCE_SPECIAL_CAR_SHARE;
                break;
            case ORDER_BIZ_CHARTER:
                mCarPaymentEntrance = CarPaymentEntrance.CAR_PAYMENT_ENTRANCE_SPECIAL_CAR_CHARTER;
                break;
            case SPECIAL_BUS_WAY:
                mCarPaymentEntrance = CarPaymentEntrance.CAR_PAYMENT_ENTRANCE_EXPRESS_CAR_WAY;
                break;
            case SPECIAL_BUS_TIME:
                mCarPaymentEntrance = CarPaymentEntrance.CAR_PAYMENT_ENTRANCE_EXPRESS_CAR_TIME;
                break;
        }
        CarPaymentInfo specialCarPaymentInfo = new CarPaymentInfo();
        specialCarPaymentInfo.setOrderId(bizOrder.getOrderSerial())
                .setCarPaymentEntrance(mCarPaymentEntrance)
                .setBizType(bizOrder.getBizTypeValue())
                .setTotalFee(bizOrder.getTotalFee() + "")
                .setDriverName(bizOrder.getDriverName())
                .setPlateNumber(bizOrder.getVehicleNo())
                .setHistoryScore(Double.valueOf((TextUtils.isEmpty( bizOrder.getAvgDriverPoint())) ? "4" : bizOrder.getAvgDriverPoint()));

        return specialCarPaymentInfo;
    }

    /**
     * 网路请求,加载当前行程数据
     */
    private void loadCurrentTripsData() {
        if (mSwipeRefreshLayout != null) {
            if (!mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(true);
                LOG.e(TAG, "loadCurrentTripsData");
                if (mDataList == null) {
                    mDataList = new ArrayList<>();
                } else {
                    mDataList.clear();
                }
                mCurrentTripsPresenter.queryCurrentTripsData(true);
            }
        }
    }

    /**
     * 在Viewpager里,每次切换Pager,调用此方法,下拉刷新
     *
     * @param isVisibleToUser true,表示切换到当前可见的fragment时
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LOG.e(TAG, "setUserVisibleHint isVisibleToUser=" + isVisibleToUser);
            loadCurrentTripsData();
        }
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_current_trips;
    }

    @Override
    protected void setupToolBar() {
    }

    @Override
    protected void initializeInjector() {
        DaggerTripComponent.builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(mActivity))
                .tripModule(new TripModule())
                .build()
                .inject(this);
    }


    @Override
    public void onRefresh() {
        setViewControlIsRefresh(true);
        isRefreshCleanList = true;
        startRefresh();
        if (mCurrentTripsPresenter != null) {
            LOG.e(TAG, "loadHistoryTripData");
            mCurrentTripsPresenter.queryCurrentTripsData(true);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        if (mCurrentTripsPresenter != null) {
            LOG.e(TAG, "loadHistoryTripData");
            mCurrentTripsPresenter.queryCurrentTripsData(false);
        }
    }

    private void setViewControlIsRefresh(boolean isRefresh) {
        if (isRefresh) {
            mCurrentTripsAdapter.setEnableLoadMore(false);
            mSwipeRefreshLayout.setEnabled(true);
        } else {
            mCurrentTripsAdapter.setEnableLoadMore(true);
            mSwipeRefreshLayout.setEnabled(false);
        }
    }

    private void resetViewControlStatus() {
        mCurrentTripsAdapter.setEnableLoadMore(true);
        mSwipeRefreshLayout.setEnabled(true);
        stopRefresh();
    }

    private void startRefresh() {
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    }

    private void stopRefresh() {
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }
}
